﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Data.Items;

namespace Workflow.Alerts.Sublayouts.ProfileSettings
{
    public partial class NetworkOperatorDtls : BaseControl, INetworkOperatorDtlsView
    {
        User user;

        #region INetworkOperatorDtlsView Members

        String INetworkOperatorDtlsView.Name
        {
            set
            {
                txtName.Text = value;
                lblCompanyName.Text = value;
            }
            get { return txtName.Text; }
        }

        String INetworkOperatorDtlsView.PostAddress
        {
            set { txtPostAddress.Text = value; }
            get { return txtPostAddress.Text; }
        }

        String INetworkOperatorDtlsView.PostCode
        {
            set { txtPostCode.Text = value; }
            get { return txtPostCode.Text; }
        }

        String INetworkOperatorDtlsView.City
        {
            set { txtPlaats.Text = value; }
            get { return txtPlaats.Text; }
        }

        String INetworkOperatorDtlsView.Code
        {
            set { txtCode.Text = value; }
            get { return txtCode.Text; }
        }

        String INetworkOperatorDtlsView.Login
        {
            set { txtLogin.Text = value; }
            get { return txtLogin.Text; }
        }

        String INetworkOperatorDtlsView.Password
        {
            set { txtPassword.Text = value; }
            get { return txtPassword.Text; }
        }

        String INetworkOperatorDtlsView.Email
        {
            set { txtEmail.Text = value; }
            get { return txtEmail.Text; }
        }

        String INetworkOperatorDtlsView.FirstName
        {
            set { txtFirstName.Text = value; }
            get { return txtFirstName.Text; }
        }

        String INetworkOperatorDtlsView.LastName
        {
            set { txtLastName.Text = value; }
            get { return txtLastName.Text; }
        }

        String INetworkOperatorDtlsView.Phone1
        {
            set { txtPhone1.Text = value; }
            get { return txtPhone1.Text; }
        }

        String INetworkOperatorDtlsView.Phone2
        {
            set { txtPhone2.Text = value; }
            get { return txtPhone2.Text; }
        }

        Boolean INetworkOperatorDtlsView.Notifications
        {
            get { return chkNotification.Checked; }
            set { chkNotification.Checked = value; }
        }

        Boolean INetworkOperatorDtlsView.Confirmations
        {
            get { return chkConfirmation.Checked; }
            set { chkConfirmation.Checked = value; }
        }

        public String ExceptionField { get; set; }

        public Int32? Id
        {
            get
            {
                //if (Request.QueryString["opId"] != null && Int32.TryParse(Request.QueryString["opId"], out id))
                //{
                //    return id;
                //}
                //else if ((Session[WorkflowConstants.CurrentUser] as User).Type == WorkflowEnums.UserType.NetworkOperator)
                //{
                //    return (Session[WorkflowConstants.CurrentUser] as User).TypeId;
                //}
                if ((Session[WorkflowConstants.CurrentUser] as User).Type == WorkflowEnums.UserType.NetworkOperator)
                {
                    return (Session[WorkflowConstants.CurrentUser] as User).TypeId;
                }
                if (Request.QueryString["opId"] != null && Int32.TryParse(Request.QueryString["opId"], out id))
                {
                    return id;
                }
                return null;
            }
            set
            {
                if (value.HasValue)
                    id = value.Value;

            }
        }

        public Boolean IsDisabled
        {
            get
            {
                return !chkDisabled.Checked;
            }
            set
            {
                chkDisabled.Checked = !value;
            }
        }

        Dictionary<int, string> INetworkOperatorDtlsView.ContractorsChoiseList
        {
            set
            {
                ddlContractorsChoise.DataSource = value;
                ddlContractorsChoise.DataValueField = "key";
                ddlContractorsChoise.DataTextField = "value";
                ddlContractorsChoise.DataBind();
                if (ddlContractorsChoise.Items.Count > 0)
                    ddlContractorsChoise.Items[0].Selected = true;
            }
        }

        Int32 INetworkOperatorDtlsView.ContractorsChoise
        {
            get
            {
                return Int32.Parse(ddlContractorsChoise.SelectedItem.Value);
            }
            set
            {
                ddlContractorsChoise.ClearSelection();
                ddlContractorsChoise.Items.FindByValue(value.ToString()).Selected = true;
            }
        }

        public event INetworkOperatorDtlsViewLoad OnPageLoad;

        public event INetworkOperatorDtlsViewUpdate OnUpdate;

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            lblEmailValidator.Visible = false;
            user = Session[WorkflowConstants.CurrentUser] as User;

            //check
            if (user.Type == WorkflowEnums.UserType.NetworkOperator &&
                Id.Value != user.TypeId)
            {
                var path = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item);
                Response.Redirect(GetNetworkId(path, user.TypeId));
            }

            PresentationManager.RegisterView(typeof(NetworkOperatorDtlsPresenter), this, new WebSessionProvider());

            Sitecore.Data.Fields.MultilistField visibleFields = (Sitecore.Data.Fields.MultilistField)Sitecore.Context.Item.Fields["CompanyVisibleFields"];
            if (visibleFields != null)
            {
                var fields = visibleFields.GetItems();
                foreach (Item item in fields)
                {
                    var field = item.Name;
                    var control = this.FindControlRecursive(field);
                    if (control != null)
                    {
                        control.Visible = true;
                    }
                }

                lblAccountInfo.Visible = (Login.Visible || Password.Visible);
            }

            bool idHasValue = Id.HasValue;
            if (!IsPostBack && idHasValue && OnPageLoad != null)
            {
                OnPageLoad();
            }

            btnContactPersons.Visible = idHasValue;
            Password.Visible = !idHasValue;

            if (user.Type == WorkflowEnums.UserType.Municipality)
            {
                DisableTextBoxes(this);
                contactButtons.Visible = false;
                btnCancel.Visible = false;
                contractor.Visible = true;
            }
        }

        private void DisableTextBoxes(Control control)
        {

            this.txtCode.Enabled = false;
            this.txtName.Enabled = false;
            this.txtPostAddress.Enabled = false;
            this.txtPostCode.Enabled = false;
            this.txtPlaats.Enabled = false;
            this.txtEmail.Enabled = false;
        }

        protected void btnNewContact_Click(object sender, EventArgs e)
        {
            //Item detailPageItem = Sitecore.Context.Item.Axes.GetChild("Contact List").Axes.GetChild("New Contact");
            Item detailPageItem = Sitecore.Context.Item.Axes.GetChild("New Contact");
            var path = Sitecore.Links.LinkManager.GetItemUrl(detailPageItem);
            if ((Session[WorkflowConstants.CurrentUser] as User).Type == WorkflowEnums.UserType.NetworkOperator)
            {
                Response.Redirect(path);
            }
            else
            {
                Response.Redirect(GetNetworkId(path));
            }
        }

        protected void btnSaveNewContact_Click(object sender, EventArgs e)
        {
            if (OnUpdate != null)
            {
                if (OnUpdate())
                {
                    //Item detailPageItem = Sitecore.Context.Item.Axes.GetChild("Contact List").Axes.GetChild("New Contact");
                    //var path = Sitecore.Links.LinkManager.GetItemUrl(detailPageItem);
                    Item detailPageItem = Sitecore.Context.Item.Axes.GetChild("New Contact");
                    var path = Sitecore.Links.LinkManager.GetItemUrl(detailPageItem);

                    if ((Session[WorkflowConstants.CurrentUser] as User).Type == WorkflowEnums.UserType.NetworkOperator)
                    {
                        Response.Redirect(path);
                    }
                    else
                    {
                        Response.Redirect(GetNetworkId(path));
                    }
                }
                else
                {
                    if (ExceptionField == "login")
                        lblLoginValidator.Visible = true;
                    else if (ExceptionField == "email")
                        lblEmailValidator.Visible = true;
                }
            }
        }

        protected void btnContactPersons_Click(object sender, EventArgs e)
        {
            Item detailPageItem = Sitecore.Context.Item.Axes.GetChild("Contact List");
            var path = Sitecore.Links.LinkManager.GetItemUrl(detailPageItem);
            if ((Session[WorkflowConstants.CurrentUser] as User).Type == WorkflowEnums.UserType.NetworkOperator)
            {
                Response.Redirect(path);
            }
            else
            {
                Response.Redirect(GetNetworkId(path));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (OnUpdate != null)
            {
                if (OnUpdate())
                {
                    if ((Session[WorkflowConstants.CurrentUser] as User).Type == WorkflowEnums.UserType.NetworkOperator &&
                        OnPageLoad != null)
                    {
                        OnPageLoad();
                    }
                    else
                    {
                        var path = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item.Parent);
                        Response.Redirect(path);
                    }
                }
                else
                {
                    if (ExceptionField == "login")
                        lblLoginValidator.Visible = true;
                    else if (ExceptionField == "email")
                        lblEmailValidator.Visible = true;
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {

            if ((Session[WorkflowConstants.CurrentUser] as User).Type == WorkflowEnums.UserType.NetworkOperator &&
                        OnPageLoad != null)
            {
                OnPageLoad();
            }
            else
            {
                var path = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item.Parent);
                Response.Redirect(path);
            }
        }

        #endregion

        #region Private Methods
        private string GetNetworkId(string path)
        {
            return string.Format("{0}?opId={1}", path, Id.Value);
        }
        private string GetNetworkId(string path, int id)
        {
            return string.Format("{0}?opId={1}", path, id);
        }
        #endregion

        #region Fields
        private int id;
        #endregion

        #region INetworkOperatorDtlsView Members




        #endregion
    }
}